import {Cask} from 'cascadium';
import {Accrual} from 'cascadium-ledger';
import {formCashflowRulesMain, formCashflowRulesAdditional, assignCashflowMain, assignCashflowAdditional} from './standard-cashflow-procedure'
import {rulesEntryMain, rulesEntryAdditional} from './predefined-rules';

const accrualEqual = ({cr: crA, dr: drA}, {cr: crB, dr: drB}) => {
  return Math.abs(crA - crB) < 1E-7 && Math.abs(drA - drB) < 1E-7
}

const colMap = [
  ['name', 'name'],
  ['dr', 'dr'],
  ['cr', 'cr'],

  ['条目', 'name'],
  ['借方发生分配至现金流量表条目', 'dr'],
  ['贷方发生分配至现金流量表条目', 'cr'],
]

const assignBehavior = {
  '': ['!不分配', '?按对方科目分配', '@按对方科目分配并重分配货币资金']
}
  

const colsMain = {
  'name':   {desc:'匹配科目', width: 250, isFilterable: true},
  'cate':   {desc:'科目性质', width: 250, isFilterable: true, attr:{options:assignBehavior}},
  'dr':     {desc:'借方发生分配至现金流量表条目', width: 300, isSortable: true},
  'cr':     {desc:'贷方发生分配至现金流量表条目', width: 300, isSortable: true},
};

const colsAdditional = {
  'name':   {desc:'条目', width: 250, isFilterable: true},
  'method': {desc:'分配行为', width: 250, isFilterable: true, attr:{options:assignBehavior}},
  'dr':     {desc:'借方发生分配至现金流量表条目', width: 300, isSortable: true},
  'cr':     {desc:'贷方发生分配至现金流量表条目', width: 300, isSortable: true},
};

const importProc = (name, sheets, book) => {

  const sheet = Object.values(sheets)[0];

  return sheet;
}

const evalMain = (books) => {

  const {data: PRIORITY_LIST} = books.find(({name}) => name === 'CASHFLOW_PRIORITY_LIST');
  const {data: CASHFLOW_TABLE} = books.find(({name}) => name === 'CASHFLOW_TABLE');
  const {data: CASHFLOW_RULES_MAIN} = books.find(({name}) => name === 'CASHFLOW_RULES_MAIN');
  const {data: UNIVERSAL} = books.find(({name}) => name === 'UNIVERSAL');
  const {data: JOURNAL} = books.find(({name}) => name === 'JOURNAL');

  if (UNIVERSAL.attr.INTEGRATED) {

    const RULES = formCashflowRulesMain(CASHFLOW_TABLE, PRIORITY_LIST, CASHFLOW_RULES_MAIN);
    assignCashflowMain(UNIVERSAL, JOURNAL, RULES, CASHFLOW_TABLE);

    CASHFLOW_TABLE.trav(({curr:{name}, succ, accrual: total, attr}) => {
      if (attr.level === 'CASHFLOW') {
				for (let {accrual: sub} of succ) {
					total.add(sub)
				}
      }
    }, 'POST')

		const totalAccrual = new Accrual();
    CASHFLOW_TABLE.trav(rec => {
      const {accrual: total, pred:{succ: siblings}, curr:{code}, attr} = rec;

      if(code.endsWith('00103') && attr.level === 'CASHFLOW') {
        siblings
					.slice(0, -1)
					.reduce((acc, {accrual}) => acc.add(accrual), total);
        totalAccrual.add(total);
      }

      if (code === '5001') {
        total.add(totalAccrual);
      }

      if (code === '6001') {
        total.add(totalAccrual);
      }

    })

    return true;

  } else {
    console.warn('现金流量表分配：待上传明细科目完毕后进行。');
  }
}

const evalAdditional = (books) => {

  console.log('EVAL ADDITIONAL');

  const {data: CASHFLOW_TABLE} = books.find(({name}) => name === 'CASHFLOW_TABLE');
  const {data: CASHFLOW_RULES_ADDITIONAL} = books.find(({name}) => name === 'CASHFLOW_RULES_ADDITIONAL');
  const {data: UNIVERSAL} = books.find(({name}) => name === 'UNIVERSAL');

  CASHFLOW_TABLE.trav((rec) => {
    if(rec.curr.code.startsWith('8') && rec.succ.every(({attr}) => attr.level !== 'CASHFLOW')) {
      rec.succ = new Cask();
    }
  })

  const RULES = formCashflowRulesAdditional(CASHFLOW_TABLE, CASHFLOW_RULES_ADDITIONAL);
  assignCashflowAdditional(CASHFLOW_TABLE, RULES, UNIVERSAL);

  CASHFLOW_TABLE.trav(({curr:{code}, accrual: total, succ}) => {

    if (code.startsWith('8') && code.length === 4) {
      succ.reduce((acc, {accrual}) => acc.add(accrual), total);
    }

  })

}

export const cashflowMainSpec = {
  name: 'CASHFLOW_RULES_MAIN',
  desc: '现金流量表分配规则 \n(主表)',
  descAddi: 'Rules for Cashflow Main',
  cate: '现金流量表分配规则',
  data: importProc('CASHFLOW_RULES_MAIN', {rulesEntryMain}),
  cols: colsMain,
  eval: {
    proc: evalMain,
		next: ['CASHFLOW_RULES_ADDITIONAL']
  },
  dataTool: {
    useUpdate: {
      displayName: '刷新',
    }
  },
  editable: true,
}

export const cashflowAdditionalSpec = {
  name: 'CASHFLOW_RULES_ADDITIONAL',
  desc: '现金流量表分配规则 \n(补充资料)',
  descAddi: 'Rules for Cashflow Additional',
  cate: '现金流量表分配规则',
  data: importProc('CASHFLOW_RULES_ADDITIONAL', {rulesEntryAdditional}),
  cols: colsAdditional,
  eval: {
    proc: evalAdditional
  },
  dataTool: {
    useUpdate: {
      displayName: '刷新',
    }
  },
  editable: true,
}
